import { Button, Dropdown, Space, Avatar, Image } from "antd"
import { useSelector } from 'react-redux/es/hooks/useSelector'
import { changeUserStatus, clearUserInfo } from "../redux/userSlice"
import { IStore } from "../redux/typings"
import styles from "../css/LoginAvatar.module.scss"
import { UserOutlined } from '@ant-design/icons';
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom"

interface IProps {
  handleLogin: () => void
}

function LoginAvatar(props: IProps) {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { isLogin, userInfo } = useSelector((state: IStore) => state.user)
  let loginStatus = null;
  // 前往个人中心
  const goToSelf = () => {
    navigate('/person')
  }
  // 退出登录
  const logOut = () => {
    dispatch(clearUserInfo({}))
    dispatch(changeUserStatus(false))
    localStorage.removeItem("token")
    // 跳转首页
    navigate("/")
  }
  if (isLogin) {
    const items = [
      {
        label: (<div onClick={goToSelf}>个人中心</div>),
        key: '0'
      }, {
        label: (<div onClick={logOut}>退出登录</div>),
        key: '1'
      }
    ]
    // 登录，显示头像
    loginStatus = (<Dropdown menu={{ items }}>
      <div className={styles.avatarContainer} >
        <Space>
          <Avatar icon={<UserOutlined />} size="large" src={<Image src={userInfo?.avatar} preview={false} />} />
        </Space>
      </div>
    </Dropdown>)
  } else {
    loginStatus = <Button type="primary" size='large' onClick={props.handleLogin}>注册/登录</Button>
  }
  return (
    <div>
      {loginStatus}
    </div>
  )
}

export default LoginAvatar
